# -*- coding: utf-8 -*-
# @Date    : 2024/2/3
# @Author  : zouy
# @Email: 874112501@qq.com
"""https://www.geetest.com/adaptive-captcha-demo"""
import json
import os
import re
import uuid
import time
from urllib.parse import urljoin

import requests
import parsel
from loguru import logger
import execjs

from main.某验.某验四代.util import DIR_PATH


def get_now():
    return str(int(time.time() * 1000))


def call_back_param():
    return "geetest_" + get_now()


def get_jsonp(text):
    jsonp_str = re.search(r"\((.*)\)", text, re.S).group(1)
    return json.loads(jsonp_str)


ss = requests.session()

ss.headers = {
    # "authority": "www.geetest.com",
    "Accept": "*/*",
    "accept-language": "zh-CN,zh;q=0.9",
    "referer": "https://www.geetest.com/adaptive-captcha",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
}

# 1. 请求验证码首页，获取link标签中的js网址
index_url = "https://www.geetest.com/adaptive-captcha-demo"
response = ss.get(index_url)
sel = parsel.Selector(response.text)
captcha_demo_link = sel.xpath('//link[contains(@href, "adaptive-captcha-demo.js")]/@href').get()
captcha_demo_url = urljoin(index_url, captcha_demo_link)
# https://www.geetest.com/_next/static/yGLsUSoSGNFNvVZFXHBOL/pages/adaptive-captcha-demo.js
logger.info(f'1.请求首页：{captcha_demo_url}')

# 2.请求第一步的js网址， 提取captchaId
headers = {'referer': 'https://www.geetest.com/adaptive-captcha-demo', }
response = ss.get(captcha_demo_url, headers=headers)
resp_text = response.text
captcha_id = re.search(r'captchaId:\s*"(.*?)",', resp_text).group(1)
logger.info(f'2.获取captchaId: {captcha_id}')  # 同平台captchaId固定：24f56dc13c40dc4a02fd0318567caef5
time.sleep(2)

# 3. 请求获取验证码相关信息
challenge = str(uuid.uuid4())
params = {
    "callback": call_back_param(),
    "captcha_id": captcha_id,
    "challenge": challenge,
    "client_type": "web",
    "risk_type": "ai",  # slide
    "lang": "zh"
}
ss.headers.update({'referer': "https://www.geetest.com/", 'host': "gcaptcha4.geetest.com"})
load_url = "https://gcaptcha4.geetest.com/load"
response = ss.get(load_url, params=params)
resp_json = get_jsonp(response.text)
json_data = resp_json['data']

load_lot_number = json_data['lot_number']  # '7a559190e40a45ff994a9cd26e54e6bb'
load_payload = json_data['payload']  # '_b-sD20eax9oEJvmoMxvFFW...'
load_process_token = json_data['process_token']  # '9aa7741f1afa76b8955a7490af2bbb7783514f8a772ceaf68caa5e604ad26867'
pow_detail = json_data['pow_detail']  # 'md5'
detail_time = json_data["pow_detail"]["datetime"]
time.sleep(2)

# 4. 提交参数进行验证
verify_url = "https://gcaptcha4.geetest.com/verify"


with open(os.path.join(DIR_PATH, 'w4.js'), 'rt', encoding='utf-8') as f:
    js_code = f.read()

ctx = execjs.compile(js_code)

w = ctx.call('genFullW4', captcha_id, load_lot_number, pow_detail)
logger.info(f'生成w参数：{captcha_id, load_lot_number, pow_detail}')
# logger.info(f'w值：{w}')
params = {
    "callback": call_back_param(),
    "captcha_id": captcha_id,
    "client_type": "web",
    "lot_number": load_lot_number,
    "risk_type": "ai",
    "payload": load_payload,
    "process_token": load_process_token,
    "payload_protocol": "1",
    "pt": "1",
    "w": w
}
response = ss.get(verify_url, params=params)
resp_json = get_jsonp(response.text)
# logger.info(resp_json)
json_data = resp_json.get('data', {})
logger.info(
    f'status >> {resp_json["status"]}  result >> {json_data.get("result")}   score >> {json_data.get("score")} ')
if json_data.get("seccode"):
    logger.success(f'验证成功：seccode >>  {json_data.get("seccode")}')
else:
    logger.warning(f'验证失败：seccode >>  {json_data.get("seccode")}')
